package com.bcu.cn.onlineexamsystem.user.controller;

import com.bcu.cn.onlineexamsystem.user.entity.User;
import com.bcu.cn.onlineexamsystem.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class UserController {

    @Autowired
    private UserService userService;


    // 登录页面
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    // 处理登录请求
    @PostMapping("/login")
    public String login(@RequestParam String userId,
                        @RequestParam String password,
                        HttpSession session,
                        Model model) {

        User user = userService.login(userId, password);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/home/manage";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }

    // 主页面
    @GetMapping("/index")
    public String index(HttpSession session, Model model) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "index";
    }

    // 退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }

    // 注册页面
    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    // 处理注册请求
    @PostMapping("/register")
    public String register(@RequestParam String userId,
                           @RequestParam String userName,
                           @RequestParam String password,
                           @RequestParam String confirmPassword,
                           @RequestParam String role,
                           @RequestParam String email,
                           Model model) {

        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "register";
        }

        User newUser = new User();
        newUser.setUserId(userId);
        newUser.setUserName(userName);
        newUser.setPassword(password);
        newUser.setRole(role);
        newUser.setEmail(email);

        if (userService.register(newUser)) {
            model.addAttribute("success", "注册成功，请登录");
            return "login";
        } else {
            model.addAttribute("error", "注册失败，用户ID或邮箱已存在");
            return "register";
        }
    }

    // 教师个人信息页面
    @GetMapping("/teacher/profile")
    public String teacherProfile(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"teacher".equals(user.getRole())) {
            return "redirect:/login";
        }
        // 重新查库，保证信息最新
        User dbUser = userService.getUserById(user.getUserId());
        model.addAttribute("user", dbUser);
        return "teacher/profile";
    }

    // 获取教师详细信息（含课程和班级，结构化返回）
    @GetMapping("/teacher/profile/info")
    @ResponseBody
    public java.util.Map<String, Object> getTeacherProfileInfo(HttpSession session) {
        User user = (User) session.getAttribute("user");
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        if (user == null || !"teacher".equals(user.getRole())) {
            result.put("success", false);
            result.put("msg", "未登录");
            return result;
        }
        User dbUser = userService.getUserById(user.getUserId());
        result.put("user", dbUser);
        result.put("courses", userService.getCoursesByTeacherId(user.getUserId()));
        result.put("classes", userService.getClassesByTeacherId(user.getUserId()));
        result.put("success", true);
        return result;
    }

    // 修改邮箱和手机号
    @PostMapping("/teacher/profile/update")
    @ResponseBody
    public String updateTeacherContact(@RequestParam String email, @RequestParam String phone, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"teacher".equals(user.getRole())) {
            return "未登录";
        }
        boolean result = userService.updateContactInfo(user.getUserId(), email, phone);
        if (result) {
            // 同步session
            user.setEmail(email);
            user.setPhone(phone);
            session.setAttribute("user", user);
            return "success";
        } else {
            return "修改失败";
        }
    }
}